<?php

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\modules\admin\models\Access;
use app\modules\admin\models\RoleAccess;
use app\modules\admin\models\UserRole;
use app\modules\admin\models\User;
use app\controllers\CommonController;

class AdminController extends CommonController
{
    public $enableCsrfValidation = false;

    public $cookieToken = "hanpy_login";
    public $current_user;
    public $allow_urls = [];//保存去的权限链接

    public $allow_action = [
        'error/forbidden',
        'error/nologin',
        'admin/user/vlogin',
        'admin/user/login',
        'admin/user/logout',
    ];

    public function beforeAction($action)
    {
        // parent::beforeAction($action); // TODO: Change the autogenerated stub
        if (in_array($action->uniqueId, $this->allow_action)) {
            return true;
        }
        if (!$this->checkLogin() && !in_array($action->uniqueId, $this->allow_action)) {
            if (Yii::$app->request->isAjax) {
                $this->jsonOut(0, '没有登录');
            } else {
                $this->redirect('/admin/user/login');
                return false;
            }
        }

        $url = $action->uniqueId;
        if (!$this->checkPerm($url)) {
            $this->redirect('/error/forbidden');
            return false;
        }

        return true;
    }

    public function checkLogin()
    {
        $cookie = Yii::$app->request->cookies;
        $authCookie = $cookie->get($this->cookieToken);
        if (!$authCookie) {
            return false;
        }

        list($authToken, $uid) = explode('#', $authCookie);
        if (!$authToken || !$uid) {
            return false;
        }

        if ($uid) {
            $userInfo = User::find()->where(['id' => $uid])->asArray()->one();
            if (!$userInfo) {
                return false;
            }

            $authTokenCookie = $this->createAuthToken($userInfo);
            if ($authToken != $authTokenCookie) {
                return false;
            }
            $this->current_user = $userInfo;
            $view = Yii::$app->view;
            $view->params['current_user'] = $userInfo;
            return true;
        }

        return false;
    }

    public function checkPerm($url)
    {
        // todo 这个地方搞一个超级管理员的判断
        if (!$this->current_user) {
            return false;
        }

        // 权限
        if (in_array($url, $this->allow_action)) {
            return true;
        }

        return in_array($url, $this->getPermList($this->current_user['id']));
    }

    public function getPermList($uid)
    {
        // ①找到用户对应的角色
        $userRoleList = UserRole::find()->where(['uid' => $uid])->asArray()->all();
        $roleIds = array_column($userRoleList, 'role_id');  // 对应的角色ID

        // ②找到对应角色对应的权限ID
        if ($roleIds) {
            $roleAccess = RoleAccess::find()->where(['role_id' => $roleIds])->asArray()->all();
            $accessIds = array_column($roleAccess, 'access_id');

            // ③找出对应的权限
            $list = Access::find()->where(['id' => $accessIds])->asArray()->all();
            if ($list) {
                foreach ($list as $info) {
                    $tmp_urls = @json_decode($info['urls'], true);
                    $this->allow_urls = array_merge($this->allow_urls, $tmp_urls);
                }
            }
        }

        if ($this->allow_urls) {
            // ④整理一下菜单, todo 这个方式不太行
            // print_r($list);die;
            $menuList = [];
            $this->allow_urls = array_filter($this->allow_urls);

            foreach ($list as $info) {
                if (!$info['is_menu']) {
                    continue;
                }
                if ($info['parent_id'] == 0) {
                    // 一级菜单
                    $menuList[$info['id']] = [
                        'title' => $info['title'],
                        'url' => '',
                    ];
                } else {
                    // 二级菜单
                    $arr_urls = json_decode($info['urls'], true);
                    $menuList[$info['parent_id']]['child'][] = [
                        'title' => $info['title'],
                        'url' => $arr_urls[0],
                    ];
                }
            }

            $view = Yii::$app->view;
            $view->params['menu_list'] = $menuList;
        }

        return $this->allow_urls;
    }

    public function createLoginStatus($userInfo)
    {
        $auth_token = $this->createAuthToken($userInfo);
        $cookie = Yii::$app->response->cookies;
        $cookie->add(new \yii\web\Cookie([
            'name' => $this->cookieToken,
            'value' => $auth_token."#".$userInfo['id'],
        ]));
    }

    public function createAuthToken($userInfo)
    {
        // todo 这个地方台简单了,以后还是需要考虑使用更好的加密方式来进行
        return md5($userInfo['id'] . $userInfo['name'] . $userInfo['email']);
    }
}